<template>
  <p-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <p-spin :spinning="confirmLoading">
      <p-form :form="form">
        <p-row>
          <!-- <p-col :span="24">
            <p-form-item label="条码字段名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input v-decorator="[ 'ruleName', validatorRules.ruleName]" placeholder="请输入条码字段名称"></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="条码字段示例" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input v-decorator="[ 'example', validatorRules.example]" placeholder="请输入条码字段示例"></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="字段长度" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input-number
                v-decorator="[ 'length', validatorRules.length]"
                placeholder="请输入字段长度"
                style="width: 100%"
              />
            </p-form-item>
          </p-col> -->
          <p-col :span="24">
            <p-form-item label="备注 " :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input v-decorator="[ 'remark', validatorRules.remark]" placeholder="请输入备注 "></p-input>
            </p-form-item>
          </p-col>
        </p-row>

        <div class="box clearfix">
          <div class="box-left">
            <div class="box-left-input">
              <p-input placeholder="Basic usage" v-model="queryFiledName" @keyup.enter="getMesBcFieldList"/>
            </div>
            
            <div class="box-left-list">

              <p-checkbox-group v-model="selectedFild" @change="onCheckboxGroupChange">
                <p-row>
                  <p-col :span="24" v-for="(item, index) in mesBcFieldList" :key="index">
                    <p-checkbox :value="item.id"  @change="onCheckboxChange">
                      {{item.filedName}}
                    </p-checkbox>
                  </p-col>
                </p-row>
              </p-checkbox-group>
            </div>

          </div>
          <div class="box-right">
            
            <p-table :columns="columns" :data-source="tableData" :pagination= "{ hideOnSinglePage: true, defaultPageSize: 10000 }">
              <a slot="name" slot-scope="text">{{ text }}</a>
              <template slot="action" slot-scope="text, record">
                <a @click="deleteSelectedFild(record.id)">删除</a>                
              </template>              
            </p-table>

          </div>
        </div>

      </p-form>
    </p-spin>
  </p-modal>
</template>

<script>
import { httpAction, getAction } from "@/api/manage";
import { SubmitOnchangMixin } from "@/mixins/SubmitOnchangMixin";
import pick from "lodash.pick";

const columns = [
  {
    title: "序号",
    dataIndex: 'id',
    key:'id',
    width:60,
    align: 'center',
  },
  {
    title: '条码字段名称',
    dataIndex: 'filedName',
    align: 'center',
    key: 'filedName',
  },
  {
    title: '条码字段示例',
    dataIndex: 'filedSample',
    align: 'center',
    key: 'filedSample',
  },
  {
    title: '字段长度',
    dataIndex: 'filedLength',
    align: 'center',
    key: 'filedLength',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width:110,
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }  
];



export default {
  name: "MesBcRuleAddModal",
  mixins: [SubmitOnchangMixin],
  components: {},
  props: {
    mainId: {
      type: String,
      required: false,
      default: "",
    },
  },
  data() {
    return {
      tableData: [],
      columns,
      selectedFild: [],
      mesBcFieldList: [],
      queryFiledName: '',

      modalState: 'edit',
      form: this.$form.createForm(this),
      title: "操作",
      width:1000,
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      validatorRules: {
        ruleName: {
          rules: [{ required: true, message: "请输入条码字段名称!" }],
        },
        example: {
          rules: [{ required: true, message: "请输入条码字段示例!" }],
        },
        length: { rules: [{ required: true, message: "请输入字段长度!" }] },
        remark: {},
      },
      url: {
        mesBcFieldList: '/mes-code/mesBcField/all',
        add: "/mes-code/mesBcRuleAdd",
        edit: "/mes-code/mesBcRuleAdd",
      },
    };
  },
  created() {
  },
  methods: {

    getMesBcFieldList(){
      const params = {
        filedName: this.queryFiledName,
      }
      getAction(this.url.mesBcFieldList, params).then( res => {
        console.log('res1234', res);
        
        this.mesBcFieldList = res.data
        this.tableData = this.mesBcFieldList.filter( ele => {
          return this.selectedFild.includes(ele.id)
        } )
        this.setSort()
      } )
    },

    onCheckboxGroupChange(checkedValues) {
      console.log('checked = ', checkedValues);
      // this.tableData = this.mesBcFieldList.filter( ele => {
      //   return checkedValues.includes(ele.id)
      // } )
    },


    onCheckboxChange({target}) {
      if (target.checked) {
        let obj; 
        this.mesBcFieldList.forEach( ele => {
          if(ele.id == target.value) {
            obj = ele
          }
        } )
        this.tableData.push(obj)
      } else {
        let indexFlag;
        this.tableData.forEach( (ele, index) => {
          (ele.id == target.value) && (indexFlag = index)
        })
        this.tableData.splice(indexFlag, 1)
      }

      this.setSort()
    },

    deleteSelectedFild(id){
      const index = this.selectedFild.indexOf(id)
      this.selectedFild.splice(index, 1)
      let index1 = null
      this.tableData.forEach( (ele, index) => {
        if (ele.id == id) {
          index1 = index
        }
      } )
      this.tableData.splice(index1, 1)

      this.setSort()
    },

    setSort(){
      this.tableData.forEach( (ele, index) => {
        this.tableData[index].sort = index + 1
      })
    },

    add() {
      this.edit({});
      
    },
    edit(record) {
      console.log(33);
      
      console.log(record);
      
      if ( Object.keys(record).length == 0) {
        this.modalState = 'add'
      }

      console.log(this.modalState);
      

      this.getMesBcFieldList()

      this.tableData = []
      this.selectedFild = []
      this.form.resetFields();
      this.model = Object.assign({}, record);

      if (record.length) {
        this.selectedFild = record.map( ele => {
          return ele.bcFieldId
        } )
        this.$nextTick(() => {
          this.form.setFieldsValue(
            pick(
              record[0],
              'remark'
            )
          );
        });
      }

      this.visible = true;
    },
    close() {
      this.$emit("close");
      this.visible = false;
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let httpurl = "";
          let method = "";
          
          console.log(229999);
          console.log(this.model);
          

          let formData = Object.assign(this.model, values);
          this.formData = Object.assign(this.model, values);
  
          this.formData = formData = this.tableData.map( ele => {
            ele.mesBarcodeRuleId = this.mainId
            ele.remark = values.remark
            ele.ruleName = ele.filedName
            ele.example = ele.filedSample
            ele.length = ele.filedLength
            ele.bcFieldId = ele.id
            ele.sort = ele.sort

            delete ele.filedName
            delete ele.filedSample
            delete ele.filedLength
            delete ele.id
            return ele
          } )


          //新增触发
          if (this.modalState == 'add') {
            console.log(222);
            console.log(this.modalState);
            
            httpurl += this.url.add;
            method = "post";
            if (this.EnhanceJS.afterAdd) {
              //新增之前
              let Obj = eval(this.EnhanceJS.afterAdd);
              new Obj(this);
            } else {
              console.log("表单提交数据", formData);
              that.modalFrom(httpurl, formData, method);
            }
          } else {
            console.log(222);
            console.log(this.modalState);
            
            //编辑触发
            httpurl += this.url.edit;
            method = "put";
            if (this.EnhanceJS.afterEdit) {
              //编辑之前
              let Obj = eval(this.EnhanceJS.afterEdit);
              new Obj(this);
            } else {
              console.log("表单提交数据", formData);
              that.modalFrom(httpurl, formData, method);
            }
          }

        }
      });
    },
    handleCancel() {
      this.close();
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'remark',
          // "timestamp",
          // "companyId",
          // "factoryId",
          // "clientId",
          // "substituteId",
          // "flag",
          // "ruleName",
          // "example",
          // "length",
          // "mesBarcodeRuleId",
          // "remark",
          // "createBy",
          // "createTime",
          // "updateBy",
          // "updateTime"
        )
      );
    },
  },
};
</script>

<style scoped>
  @import '~@assets/less/common.less';
</style>

<style lang="less" scoped>
.box {
  .box-left {
    padding-left: 5px;
    float: left;
    width: 200px;
    border: 1px solid #ddd;
    .box-left-input {
      padding: 5px 5px 10px 0;
    }
    .box-left-list {
      height: 400px;
      overflow: auto;
    }
  }
  .box-right {
    float: right;
    width: 700px;
    border: 1px solid #ddd;
  }
}

</style>

